package com.peanut.service.impl;

import com.peanut.entity.ChannelType;
import com.peanut.entity.vo.ChannelTypeVO;
import com.peanut.mapper.ChannelTypeMapper;
import com.peanut.service.ChannelTypeService;
import com.spring.annotation.Autowired;
import com.spring.annotation.Service;

import java.time.LocalDateTime;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class ChannelTypeServiceImpl implements ChannelTypeService {
	@Autowired
	private ChannelTypeMapper mapper;
	
	
	@Override
	public List<ChannelTypeVO> queryChannelType() {
		List<ChannelTypeVO> topType = mapper.queryTopType();
		List<ChannelTypeVO.ChannelTypeSonVO> sonType = mapper.querySonType();
		
		for (ChannelTypeVO channelTypeVO : topType) {
			channelTypeVO.setChildren(sonType.stream()
											 .filter( e -> channelTypeVO.getId().equals(e.getParentId()))
											 .collect(Collectors.toList()));
		}
		return topType;
	}
	
	@Override
	public List<ChannelType> queryAllChannelType() {
		return mapper.selectAll();
	}
	
	@Override
	public boolean updateById(ChannelType channelType) {
		return mapper.updateById(channelType) == 1;
	}
	
	@Override
	public boolean add(ChannelType channelType) {
		channelType.setCreateTime(LocalDateTime.now());
		return mapper.insert(channelType) > 0;
	}
	
	@Override
	public boolean delete(int id) {
		// 删除条件是 当前id 不能被其他 parentId 引用
		// 同时不能被 Channel 使用到  才能删除
		
		// 还没有测试
		if (mapper.query1(id) == 0 && mapper.query2(id) == 0) {
			return mapper.deleteById(id) > 0;
		}
		return false;
	}
}
